import axios from 'axios'

import {useUserStore} from "@/stores/User.js";
import {ElMessage} from "element-plus";
let userStore = null; // 延迟在请求拦截器中初始化，否则报错“getActivePinia()“ was called but there was no active Pinia.”

export const BASE_URL = import.meta.env.VITE_API_BASE_URL;

const http = axios.create({
    baseURL: import.meta.env.VITE_API_BASE_URL,
    timeout: 5000,
    headers: {

    }
});



// 请求拦截
http.interceptors.request.use((config)=>{
    if(!userStore){
        userStore = useUserStore();
    }

    // 判断是否登录，并添加token到请求头
    if(userStore.isLogin()){
        console.log('axios 已登录',userStore.getToken());
        config.headers['authorization'] = userStore.getToken();
    }else{
        console.log('未登录');
    }

    console.log('axios请求',config);

    return config;
},(error)=>{
    console.log("axios请求错误",error);
    return Promise.reject(error);
});

// 响应拦截
http.interceptors.response.use((response)=>{
    console.log('axios响应',response);
    if(response.data.code !== 200){
        // 未登录
        ElMessage.error(response.data.message);
    }
    return response;
},(error)=>{
    console.log("axios响应错误",error);
    console.log('响应状态:',error.response);
    if(error.response.status === 403) {
        // 未登录

    }

    return Promise.reject(error);
});

export default http;
